/**
 * 数据可以是只读数据, 即不可修改
 */
let activeEffect
const bucket = new WeakMap()
let effectStack = []
const ITERATE_KEY = Symbol()
function track(target, key) {
  let depsMap = bucket.get(target)
  if (!depsMap) {
    bucket.set(target, (depsMap = new Map()))
  }
  let deps = depsMap.get(key)
  if (!deps) {
    depsMap.set(key, (deps = new Set()))
  }
  if (activeEffect) {
    deps.add(activeEffect)
    activeEffect.deps.push(deps)
  }
}

function trigger(target, key, type) {
  const depsMap = bucket.get(target)
  if (!depsMap) return
  const effects = depsMap.get(key)
  const effectsToRun = new Set()
  effects &&
    effects.forEach((effect) => {
      if (effect !== activeEffect) {
        effectsToRun.add(effect)
      }
    })

  if (type === 'ADD' || type === 'DELETE') {
    const iterateEffects = depsMap.get(ITERATE_KEY)

    iterateEffects &&
      iterateEffects.forEach((effect) => {
        if (effect !== activeEffect) {
          effectsToRun.add(effect)
        }
      })
  }

  effectsToRun.forEach((effect) => {
    if (effect.options.schedule) {
      effect.options.schedule(effect)
    } else {
      effect()
    }
  })
}
// 增加第三个参数, 是否只读, 默认:false
function createReactive(data, isShallow = false, isReadonly = false) {
  const obj = new Proxy(data, {
    get(target, key, receiver) {
      if (key === 'raw') {
        return target
      }
      const res = Reflect.get(target, key, receiver)
      // 如果是只读, 则不记录其副作用函数
      if (!isReadonly) {
        track(target, key)
      }

      if (isShallow) {
        return res
      }

      if (typeof res === 'object' && res !== null) {
        // 如果是只读, 则递归的是深只读逻辑
        // 注意递归传的是res不是obj!!!!
        return isReadonly ? createReactive(res, false, true) : createReactive(res)
      }

      return res
    },
    set(target, key, value, receiver) {
      // 只读属性不可设置
      if (isReadonly) {
        console.log(`属性${key}为只读`)
        return true
      }
      const oldValue = target[key]
      const type = Object.prototype.hasOwnProperty.call(target, key) ? 'SET' : 'ADD'
      const res = Reflect.set(target, key, value, receiver)
      if (receiver.raw === target) {
        if (oldValue !== value && (oldValue === oldValue || value === value)) {
          trigger(target, key, type)
        }
      }
      return res
    },
    has(target, key) {
      return Reflect.has(target, key)
    },
    ownKeys(target) {
      track(target, ITERATE_KEY)
      return Reflect.ownKeys(target)
    },
    deleteProperty(target, key) {
      // 只读数据不得删除
      if (isReadonly) {
        console.log(`${key}是只读数据不可删除`)
        return true
      }
      const hadKey = Object.prototype.toString.call(target, key)
      const res = Reflect.deleteProperty(target, key)
      if (hadKey && res) {
        trigger(target, key, 'DELETE')
      }
      return res
    }
  })
  return obj
}
function cleanup(effectFn) {
  for (let i = 0; i < effectFn.deps.length; i++) {
    const deps = effectFn.deps[i]
    deps.delete(effectFn)
  }
  effectFn.deps.length = 0
}

function effect(fn, options = {}) {
  const effectFn = () => {
    cleanup(effectFn)
    activeEffect = effectFn
    effectStack.push(effectFn)
    const res = fn()
    effectStack.pop()
    activeEffect = effectStack[effectStack.length - 1]
    return res
  }
  effectFn.deps = []
  effectFn.options = options
  if (!options.lazy) {
    effectFn()
  }
  return effectFn
}

// 只读函数
// 深只读
function readonly(obj) {
  return createReactive(obj, false, true)
}

// 浅只读
function shallowReadonly(obj) {
  return createReactive(obj, true, true)
}

// 测试
const obj1 = readonly({ info: { d: 'jerry' } })

const obj2 = shallowReadonly({ info: { s: 'tom' } })

// effect(() => {
//   console.log(obj1.info.d, 'deep result')
// })

// obj1.info.d = '1'

effect(() => {
  console.log(obj2.info.s, 'shallow result')
})

obj2.info.s = '2'
